package com.wwlwxg.forkjoin;

import java.util.concurrent.RecursiveTask;

public class ForkjoinDemo extends RecursiveTask<Long> {

    private Long start;
    private Long end;

    // 临界值
    private Long temp = 10000L;

    public ForkjoinDemo(Long start, Long end) {
        this.start = start;
        this.end = end;
    }

    @Override
    protected Long compute() {
        if(end - start < temp) {
            Long sum = 0L;
            for (Long i = start; i <= end; i++) {
                sum += i;
            }
            return sum;
        } else {        // forkjoin
            long middle = (end + start) / 2;
            ForkjoinDemo demo1 = new ForkjoinDemo(start, middle);
            demo1.fork();
            ForkjoinDemo demo2 = new ForkjoinDemo(middle + 1, end);
            demo2.fork();
            return demo1.join() + demo2.join();
        }
    }

}
